import React from 'react'
import {Button, Modal,Row,Col ,Input} from 'antd'
import {WeaSearchGroup, WeaInput, WeaFormItem, WeaTableEditable, WeaTable, WeaLocaleProvider, WeaBrowser} from 'ecCom'
import { inject, observer} from 'mobx-react';
import {toJS} from "mobx";
const getLabel = WeaLocaleProvider.getLabel;

@inject("myCreateForm")
@observer
class CCTableTd extends React.Component{
    constructor(props){
        super(props);
        this.state={
            isorder:this.props.myCreateForm.isorder,//控制是否有序
        }
    }

    componentDidMount = () =>{
        $("#cc_ldwa_hhhhh_2018_9_26").css({"margin-left":"-55px","width": $("#cc_wldn_lllll_2018_9_26").parent().parent().width()+"px"});
        $("#cc_ldwa_hhhhh_2018_9_26 .ant-table-body").css({"overflowX":"auto"});
    }

    /**
     * 点击签署信息是否排序
     * @param data
     */
    fnOnChage = (data) => {
        //修改这里是使用dom操作
        let sl = $("#signOrder").val();
        if(sl == undefined) sl = data.target.selectedIndex;
        const { myCreateForm} = this.props;
        if (sl=="0"||sl == 0) {
            this.setState({isorder:false});
            const {tabledata} = myCreateForm;
            tabledata.map((val,i) => { tabledata[i].qssx_=""; });
            myCreateForm.isorder=false;
        }
        if (sl=="1" || sl ==1) {
            this.setState({isorder:true});
            myCreateForm.isorder=true;
        }
    }

    /** 可编辑表格数据的修改 */
    fnOnChageDatas = (data, other) => {
        const { myCreateForm} = this.props;
        myCreateForm.setTabledata(data);
    }

    /**
     * 取消每一行的选则框
     * @param rowSelection
     */
    getRowSelection = rowSelection => {
        const sel = { ...rowSelection };
        sel.getCheckboxProps = record => {
            return { disabled: record.id === '1' };
        };
    }

    fnAdditionalChange =(ids_value, names_value, datas, row, id) =>{
        const {  myCreateForm} = this.props ;
        const {tabledata,setTabledata} = myCreateForm;
        let initialDatas = tabledata;
        let updateid = row && row.id;
        initialDatas && initialDatas.map(item=>{
            if(item.id == updateid) {
                item[id+"span"] = names_value;
                item[id] = ids_value
            }
        })
        setTabledata(initialDatas);
    }

    /**
     * 重新组装浏览按钮
     * @param value 浏览按钮显示值 span       非必填
     * @param row 可编辑表格中的行数据        必填
     * @param index 行号                     非必填
     * @param id   数据源id，浏览按钮数据id   必填
     * @param browtype  浏览按钮的type值      必填[默认为表单字段]
     * @param title 浏览按钮打开后的title     必填[默认表单字段]
     * @returns {{props: {rowSpan: number}, children: string}}
     */
    fnSetPrivateBrow =(value, row, index, id, browtype = "formField", title = "表单字段", viewAttr = 2 , myparams={}) =>{
        let replacedatas = toJS(row[id+"map"]);
        const {   workflowid } = this.props ;
        const params ={workflowid: workflowid, workflowId:workflowid, tableIndex:"main", mainOnly:"1", ...myparams};
        const obj = {props:{rowSpan:1}, children:""};
        const { ispublic=false,serverType} = this.props ;

        if(id == "mobileField" && !ispublic && row.signerType == 0){
            let sealMobileField = toJS(row["sealMobileFieldmap"]);
            obj.children = (<div>
                <span>{getLabel(513642,"企业签章")}:</span>
            <WeaBrowser
            type={browtype}
            hasAdvanceSerach={true}
            title={title}
            isSingle={false}
            isMultCheckbox={false}
            viewAttr={viewAttr}
            dataParams={params}//查询参数
            conditionDataParams={params}
            completeParams={params}
            destDataParams={params}
            replaceDatas={sealMobileField}
            onChange={(ids, names, datas) => {
                this.fnAdditionalChange(ids, names, datas, row, "sealMobileField")
            }}
            >
            </WeaBrowser>
            <span>{getLabel(513643,"个人签字")}:</span>
            <WeaBrowser
            type={browtype}
            hasAdvanceSerach={true}
            title={title}
            isSingle={false}
            isMultCheckbox={false}
            viewAttr={viewAttr}
            dataParams={params}//查询参数
            conditionDataParams={params}
            completeParams={params}
            destDataParams={params}
            replaceDatas={replacedatas}
            onChange={(ids, names, datas) => {
                this.fnAdditionalChange(ids, names, datas, row, id)
            }}
        >
        </WeaBrowser>
        </div>
        );
        }else{
        obj.children =(
            <WeaBrowser
            type={browtype}
            hasAdvanceSerach={true}
            title={title}
            isSingle={false}
            isMultCheckbox={false}
            viewAttr={viewAttr}
            dataParams={params}//查询参数
            conditionDataParams={params}
            completeParams={params}
            destDataParams={params}
            replaceDatas={replacedatas}
            onChange={(ids, names, datas) => {
                this.fnAdditionalChange(ids, names, datas, row, id)
            }}
            >
            </WeaBrowser>);
        }
        return obj;
    }
    render(){
        const {isorder} = this.state;
        const { ispublic=false, workflowid, myCreateForm} = this.props ;
        const {tabledata, cellss, alldatas} = myCreateForm;
        const {form} = alldatas;
        let initialDatas = tabledata;
        const  columns= this.fnGetColumns();
        let isshowtitle = !(form.getFormDatas() && form.getFormDatas().signNode);
        let itmes={
            title:getLabel(18625,"基本信息"),
            items:[
                {com:
                    <WeaFormItem   labelCol={{span: 0}} wrapperCol={{span:24}}>
                        <div id="cc_ldwa_hhhhh_2018_9_26"  style={{border:"1px solid #d9d9d9"}}>
                            <WeaTableEditable
                                ref={el=>{this.table = el;}}
                                datas={initialDatas}
                                className={"tabcss"}
                                columns={columns}
                                showAdd={true}
                                showDelete={true}
                                showCopy={false}
                                cells={cellss}
                                showTitle={isshowtitle}
                                willAdd = {this.willAdd}
                                onChange={this.fnOnChageDatas}
                                getRowSelection={isshowtitle?{disabled:true}:this.getRowSelection} //禁用第一列选中框
                                // validator={this.signnamerule()} 非自定义验证方法
                            />
                        </div>
                    </WeaFormItem>
                },
            ]
        }
        return(
            <div id="cc_wldn_lllll_2018_9_26">
                <WeaSearchGroup
                    items={itmes.items} showGroup={true} col={1}/>
            </div>
        )
    }

    /**
     * 新增的钩子事件，默认给定新增的数据信息
     * @param datas
     * @param addData
     * @returns {*}
     */
    willAdd = (datas, addData) => {
        return datas.map(data => {
            if (addData.id === data.id) return { ...data, signerType: "0" , isSign:"true"};
            return data;
        });
    }

    /**
     * 得到列头数据
     * @returns {*}
     */
    fnGetColumns = () => {
        const {isorder} = this.state;
        const { ispublic=false, workflowid, myCreateForm} = this.props ;
        const {signnatorys,alldatas, hiddenid} = myCreateForm;//签署方下拉选择
        const {form} = alldatas;
        let isedit = form.getFormDatas() && form.getFormDatas().signNode;
        const that = this;
        // let params = {workflowid: workflowid, workflowId:workflowid, tableIndex:"main", mainOnly:"1", tabletype:"0"};
        //TODO-start最好从后端生成返回给前端使用， 这里涉及到渲染所以展示在此处直接写
        const  columns= [
            {
                title: <span >{getLabel(386001, "合同签署节点")}</span>,
                dataIndex: "table_signnode",
                width:"20",
                com:[{ type: 'BROWSER', key: 'table_signnode' } ],
                aboutsignNode: true,
                render(value, row, index) {
                    return(that.fnSetPrivateBrow(value, row, index, "table_signnode", "workflowNode", getLabel(386001, "合同签署节点"), 3));
                }
            },
            {
                title: <span id={"cc_test"}>{getLabel(513833,"签署方类型")}</span>,
                dataIndex: 'signerType',
                width:"12%",
                com: [{ type: 'SELECT', key: 'signerType' ,options:signnatorys, viewAttr:isedit?1:2} ],
            }, {
                title: <span>{getLabel(386028,"是否签署")}</span>,
                dataIndex: 'isSign',
                width: '8%',
                // 显示全选
                showCheckAll: false,
                // 自定义值类型
                checkVauleType: [true, false],
                aboutsevertype: true,
                com: [{ type: 'CHECKBOX', key: 'isSign' },],
            },
            {
                title: <span>{getLabel(386018,"签署顺序")}<select onChange={this.fnOnChage}  id="signOrder" value={isorder?1:0}><option   value="0" >{getLabel(386020,"无序签署")}</option><option   value="1">{getLabel(386019,"顺序签署")}</option></select></span>,
                dataIndex: isorder?'qssx_':'qssx',
                width:"14%",
                aboutsevertype: true,
                com: [isorder? { type: 'inputnumber', key: 'qssx_' }: { type: 'text', key: 'qssx' }],
            },
            {
                title: <span>{getLabel(386013,"签署方姓名")}</span>,
                width: "12%",
                dataIndex: 'nameField',
                com: [{
                    type: 'BROWSER',
                    key: 'nameField',
                 /*   browserConditionParam: {
                        type:"conlocworkflowfield",
                        viewAttr:3,
                        dataParams:{...params},
                        isSingle:false,
                        title:getLabel(386013,"签署方姓名"),
                        isMultCheckbox:false,
                        conditionDataParams:{...params},
                        completeParams:{...params},
                        destDataParams:{...params},
                    },*/
                } ],
                render(value, row, index) {
                    // console.log(row.isSign,  isedit);
                    // let issigntrue = (isedit?false : true) && row.isSign;
                    let viewattr = 2;
                    //私有-都必填 **注意修改这里记得同步修改doValidate方法，因为目前采用手动验证方法
                    if(!ispublic) { viewattr = 3;}
                    //公有--对方企业，以及个人必填
                    if((row.signerType == 1|| row.signerType == 2)  && ispublic) { viewattr = 3;}
                    if(isedit && viewattr == 3) {
                        if(!row.isSign) {
                            viewattr = 2;
                        }
                    }
                    return(that.fnSetPrivateBrow(value, row, index, "nameField", "conlocworkflowfield", getLabel(386013,"签署方姓名"), viewattr));
                }
            },
            {
                title:<span>{getLabel(513832,"签署人联系方式")}</span>,
                width: "12%",
                dataIndex: 'mobileField',
                com: [{ type: 'BROWSER', key: 'mobileField', browserConditionParam: { type: "formField?workflowId="+workflowid+"&tableIndex=main&" }}],
                render(value, row, index) {
                    return(that.fnSetPrivateBrow(value, row, index, "mobileField", "conlocworkflowfield", getLabel(386014,"签署人手机号")));
                },
            },
            {
                // title:<span>{getLabel(386091,"签署动作（自定义多选）")}</span>,
                title:<span>{getLabel(500204,"签署动作") }</span>,
                width: "12%",
                dataIndex: 'issignaction',
                key: "issignaction",
                com: [{ type: 'TEXT', key: 'issignaction'}],
                render(value, row, index) {
                    //只有本方企业显示浏览按钮，其他显示空文本
                    if(row.signerType == 2 ){ return ""; }
                    return(that.fnSetPrivateBrow(value, row, index, "issignaction", "conlocworkflowfield", getLabel(386091,"签署动作（自定义多选）"),null, {fieldtype:"signAction"}));
                },
            },
            {
                title:<span>{getLabel(	500207,"签署位置关键字")}</span>,
                width: "13%",
                dataIndex: 'keywordfield',
                com: [{type: 'BROWSER', key: 'keywordfield', browserConditionParam: { type: "formField?workflowId="+workflowid+"&tableIndex=main&"}}],//TODO 待处理
                render(value, row, index) {
                    return(that.fnSetPrivateBrow(value, row, index, "keywordfield", "conlocworkflowfield", getLabel(	500207,"签署位置关键字")));
                },
            },
            {
                title:<span>{getLabel(	511111,"签署印章")}</span>,
                width: "12%",
                dataIndex: 'signSealField',
                com: [{type: 'BROWSER', key: 'signSealField', browserConditionParam: { type: "formField?workflowId="+workflowid+"&tableIndex=main&"}}],//
                render(value, row, index) {
                        if(row.signerType != 0 ){ return ""; }
                        return(that.fnSetPrivateBrow(value, row, index, "signSealField", "conlocworkflowfield", getLabel(	511111,"签署印章")));
                },
            }
        ];
        //TODO-end
        let column = [];
        columns && columns.map(item => {
            let ok = !(isedit && item.aboutsignNode);//form存在签署节点，表格中不需要签署节点

            if(hiddenid && ok) {//编辑时添加是否签署，与签署顺序选择框
                if(!(!isedit && item.aboutsevertype)) {
                    column.push(item);
                }
            }
            // if(!hiddenid && !item.aboutsevertype && ok) {
           else  if(!hiddenid && !item.aboutsevertype && ok ) {
                column.push(item);
            }
        });
        return column;
    }
}
export default CCTableTd